package org.example;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 动态服务器上下线
 */
public class DynamicServerUpAndDownClient {

    private String connectString = "10.211.55.102:2181,10.211.55.103:2181,10.211.55.104:2181";
    private int sessionTimeout = 2000;
    private ZooKeeper zkClient;

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        DynamicServerUpAndDownClient dc = new DynamicServerUpAndDownClient();
        // 获取 zk连接
        dc.connectZooKeeper();

        dc.getServerList();

        dc.business();
    }

    private void business() throws InterruptedException {
        Thread.sleep(Long.MAX_VALUE);
    }

    private void getServerList() throws InterruptedException, KeeperException {
        List<String> children = zkClient.getChildren("/servers", true);
        List<String> servers = new ArrayList<>();
        for (String child : children) {
            byte[] data = zkClient.getData("/servers/" + child, false, null);
            servers.add(new String(data));
        }

        System.out.println(servers);
    }


    void connectZooKeeper() throws IOException {
        zkClient = new ZooKeeper(connectString, sessionTimeout, event -> {
            // 监听节点变化
            try {
                getServerList();
            } catch (KeeperException | InterruptedException e) {
                throw new RuntimeException(e);
            }

        });
    }
}

